/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import path from 'path';

import { hvigorCore } from '../../../../../../index.js';
import { nodeConfigPathInfo } from '../../../../../common/node-config-path-info.js';
import { Module, Project } from '../../../../external/core/hvigor-core-node.js';
import { HvigorLogger } from '../../../../log/hvigor-log.js';
import { findSyncTaskPathsForNode } from '../../sync.js';
import { AbstractExecutePipeline } from './abstract-execute-pipeline.js';
import { TaskExecuteOptions } from './execute-mode-factory.js';

const _log = HvigorLogger.getLogger('hvigor-module-pipeline');

/**
 * 执行所有Module的Pipeline
 *
 * @since 2022/6/20
 */
export class ExecuteModulePipeline extends AbstractExecutePipeline {
  private executeModules: Module[] = [];

  constructor(project: Project, taskOptions: TaskExecuteOptions) {
    super(project, taskOptions);
    this.init();
  }

  /**
   * 根据命令行和工程的配置，初始化-m 为module下时需要执行的所有模块集合
   *
   * @private
   */
  private init(): void {
    const modules = hvigorCore.getExtraConfig().get('module');
    if (modules === undefined) {
      this.executeModules = this.project.getAllSubModules();
    } else {
      this.shouldCheckTask = true;
      modules.split(',').forEach((moduleAndTargetName: string) => {
        const values: string[] = moduleAndTargetName.split('@');
        const moduleName: string = values[0];
        const module: Module | undefined = this.project.findModuleByName(moduleName);
        if (module === undefined) {
          if (nodeConfigPathInfo.checkExcludeNode(moduleName)) {
            _log.printErrorExit('UNKNOWN_MODULE_IN_COMMAND_LINE_HVIGORCONFIG',
              [moduleName, path.resolve(this.project.getNodeDir(), 'hvigorconfig.ts')]);
          }
          _log.printErrorExit('UNKNOWN_MODULE_IN_COMMAND_LINE_BUILD_PROFILE',
            [moduleName, this.project.getBuildProfilePath()]);
        }
        this.executeModules.push(module!);
      });
    }
  }

  public findPipeAllNeedExecuteSyncTasks(): string[] {
    const allSyncTasks: string[] = [];
    this.executeModules.forEach((value) => {
      allSyncTasks.push(...findSyncTaskPathsForNode(value));
    });
    return allSyncTasks;
  }

  public findPipeAllNeedExecuteTasks(): string[] {
    return this.findAllNeedExecuteTasksForNodes([...this.executeModules]);
  }

  public recordTraceData(): void {
  }
}
